from Accounting.Fee.FeeBase import Fee
from Error.ExtendError import OfficialFee_NA
from DataAccess.DBConnFactory import DBConnFactory
from string import Template


class MiscFee(Fee):
	def __init__(self, ref_date, entity, subtype, is_payment_date, is_redem, curncy):
					
		Fee.__init__(self, ref_date, curncy, is_payment_date, is_redem, entity)		
		self.fee_subtype = subtype
		#self.ctgy = category
		
	def category(self):
		if not hasattr(self, 'ctgy'):
			cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
			sql_tpl = Template('''select category from fee_conf 
							where entity='${ENTITY}' 
								and subtype='${TP}' 
								and class='MiscFee' ''')
			sql_text = sql_tpl.substitute(ENTITY=self.entity.get_entity_id(), 
										TP=self.type())
			cursor.execute(sql_text)
			r = cursor.fetchone()
			if r and len(r)>0:
				self.ctgy = r[0]
			else:
				#print sql_text
				raise RuntimeError(), ('sql text='+sql_text)
									
		return self.ctgy
				
	def type(self):
		return self.fee_subtype		
		
	def calculate(self):
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()
		sql_tpl = Template('''select amount,curncy from fee 
							where ref_date=TO_DATE('${DATE}','yyyy-mm-dd') 
								and entity='${ENTITY}' 
								and subtype='${TP}' 
								and official='T' ''')
		sql_text = sql_tpl.substitute(DATE=self.ref_date.isoformat(), 
									ENTITY=self.entity.get_entity_id(), 
									TP=self.type())	
		cursor.execute(sql_text)
		r = cursor.fetchone()
		#print 'debug,sql_text', sql_text
		#print 'debug,fetchone()', r
		
		if r and len(r)>0:
			self.amt = r[0]
			self.curncy = r[1]
		else:
			self.amt = 0.00
			#raise OfficialFee_NA(), ('sql text='+sql_text)
		
	def persistence(self):
		#DO NOTHING
		return